package com.morningstar.qs.basic.db.util;

import java.io.File;
import java.util.logging.Logger;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.morningstar.qs.api.basic.common.config.GlobalConfig;

public class HibernateUtil {

	private static Logger log = Logger.getLogger(HibernateUtil.class.getName());

	private static final String hibernateFile = GlobalConfig.getProperty(
			"hibernate", "config-file");
	private static Object lock = new Object();

	private static SessionFactory sessionFactory;

	public static Session getSession() {
		if (sessionFactory == null)
			initHibernateConfig();
		return sessionFactory.openSession();
	}

	private static void initHibernateConfig() {
		if (hibernateFile == null)
			throw new NullPointerException(
					"Hibernate configuration file is not specified.");
		synchronized (lock) {
			if (sessionFactory == null) {
				File file=new File(hibernateFile);
				sessionFactory = new Configuration().configure(file)
						.buildSessionFactory();
			}
		}

	}

}
